package cn.kailangtu.myapplication;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.navigation.fragment.NavHostFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.kailangtu.myapplication.data.Address;
import cn.kailangtu.myapplication.data.Tool;
import cn.kailangtu.myapplication.data.yemian;
import cn.kailangtu.myapplication.databinding.FragmentSecond1Binding;
import cn.kailangtu.myapplication.databinding.FragmentSecondBinding;
import cn.kailangtu.myapplication.events.SerialData;
import cn.kailangtu.myapplication.events.Shuaxing灯Event;
import cn.kailangtu.myapplication.events.刷新动能回收力度;
import cn.kailangtu.myapplication.events.发送CAN数据;
import cn.kailangtu.myapplication.fragment.BaseFragment;
import cn.kailangtu.myapplication.tools.MediaPlayerUtils;
import cn.kailangtu.serialport.CommonUtils;

public class SecondFragment1 extends BaseFragment {

    private FragmentSecond1Binding binding;




    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        binding = FragmentSecond1Binding.inflate(inflater, container, false);
        return binding.getRoot();


    }


    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
        String t=format.format(new Date());
        binding.TextViewTime.setText(t);

        binding.buttonSet1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(SecondFragment1.this)
                        .navigate(R.id.action_SecondFragment1_to_FirstFragment);
            }
        });
        MediaPlayerUtils.getInstance().playZhuanxiangEnd();



        binding.rbPower0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reset0x201();
            }
        });

        binding.rbPower1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reset0x201();
            }
        });

        binding.rbPower2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reset0x201();
            }
        });

        binding.tvClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickCount++;
                if(clickCount >= 20)
                {
                    clickCount = 0;
                    getActivity().finish();
                }
            }
        });

        binding.btnEntryClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

        binding.btnEntryDebug.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    isView = !isView;
                    if(isView)
                    {
                        binding.tvData.setVisibility(View.VISIBLE);
                        binding.tvData1.setVisibility(View.VISIBLE);
                        binding.btnEntryDebug.setText("退出诊断");
                    }
                    else
                    {
                        binding.tvData.setVisibility(View.GONE);
                        binding.tvData1.setVisibility(View.GONE);
                        binding.btnEntryDebug.setText("进入诊断");
                    }
            }
        });

    }

    int clickCount = 0;

    private void reset0x201()
    {
        byte[] data = new byte[8];
        if(binding.rbPower0.isChecked())
        {
            data[0] = 0;
        }
        else if(binding.rbPower1.isChecked())
        {
            data[0] = 1;
        }
        else if(binding.rbPower2.isChecked())
        {
            data[0] = 2;
        }
        Log.d("SHOOTLEE_0x201","DATA:"+data[0]);
        EventBus.getDefault().post(new 发送CAN数据(new byte[]{0x00,0x00,0x02,0x01},data));
        lastSendTime = System.currentTimeMillis();
    }

    long lastSendTime = 0;


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(刷新动能回收力度 event)
    {
        if((System.currentTimeMillis() - lastSendTime) > 1000) {
            if (event.getValue() == 0) {
                binding.rgPowerContainer.check(R.id.rbPower0);
            } else if (event.getValue() == 1) {
                binding.rgPowerContainer.check(R.id.rbPower1);
            } else if (event.getValue() == 2) {
                binding.rgPowerContainer.check(R.id.rbPower2);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SerialData event){



        yemian.getInstance().页面2(1,this.getActivity());

        if(event.getAtime()!=null) {
            binding.TextViewTime.setText(event.getAtime());
        }
        if(isView) {
            binding.tvData.setText(getData());
            binding.tvData1.setText(getData1());
        }
    }

    boolean isView = false;

    public static int booleanToInt(boolean boolValue) {
        // 使用三元运算符将boolean转换为int
        return boolValue ? 1 : 0;
    }


    public static int byteBitToInt(int source,int displacement)
    {
        return (source >> displacement) & 3;
    }

    //BYTE转成bool
    public  boolean[] byteToBooleanArray(byte b) {
        boolean[] boolArray = new boolean[8];
        for (int i = 0; i < 8; i++) {
            // 通过位运算检查当前位是否为1
            boolArray[i] = ((b >> i) & 1) == 1;
        }
        return boolArray;
    }

    //合并成int
    public static int combineBytesToInt(byte byte1, byte byte2) {
        // 将byte1左移8位，空出的低位由byte2填充
        return (byte1 << 8) | (byte2 & 0xFF);
    }

    //EventBus  推出
    @Override
    public void onStop(){
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }


    private String getData()
    {

        /*

        Bit0 = 座位开关                   Bit1 = 脚刹
Bit2 = 前进挡位                Bit3 = 后退挡位                Bit4 = 手刹                    Bit5 = 龟速                         Bit6 = 右转向灯                          Bit7 = 左转向灯                       Bit8 = 双闪灯                        Bit9 = 示廓灯                    Bit10=  近光灯                           Bit11 = 远光灯                Bit12 = 后雾灯                          Bit13 = 安全接近                         Bit14 = 安全接近向前              Bit15 = 安全接近向后
bit16 = 真空泵报警（显示屏）
bit17 = 刹车油液位低（显示屏）

         */

        StringBuilder sb = new StringBuilder();
        sb.append("驱动器故障代码："+Address.getInstance().getData(Address.can281,1,1,"无符号"));
        sb.append("\r\n电机故障01:"+ Address.getInstance().getData(Address.can281,4,2,"无符号"));
        sb.append("\r\n座位开关:"+(Address.getInstance().getDataBit(Address.can381,0,0)?"1":"0"));
        sb.append("\r\n前进挡位:"+(Address.getInstance().getDataBit(Address.can381,0,2)?"1":"0"));
        sb.append("\r\n后退挡位:"+(Address.getInstance().getDataBit(Address.can381,0,3)?"1":"0"));
        sb.append("\r\n手刹:"+(Address.getInstance().getDataBit(Address.can381,0,4)?"1":"0"));
        sb.append("\r\n龟速:"+(Address.getInstance().getDataBit(Address.can381,0,5)?"1":"0"));
        sb.append("\r\n右转向灯:"+(Address.getInstance().getDataBit(Address.can381,0,6)?"1":"0"));
        sb.append("\r\n左转向灯:"+(Address.getInstance().getDataBit(Address.can381,0,7)?"1":"0"));

        sb.append("\r\n双闪灯:"+(Address.getInstance().getDataBit(Address.can381,1,0)?"1":"0"));
        sb.append("\r\n示廓灯:"+(Address.getInstance().getDataBit(Address.can381,1,1)?"1":"0"));
        sb.append("\r\n近光灯:"+(Address.getInstance().getDataBit(Address.can381,1,2)?"1":"0"));
        sb.append("\r\n远光灯:"+(Address.getInstance().getDataBit(Address.can381,1,3)?"1":"0"));
        sb.append("\r\n后雾灯:"+(Address.getInstance().getDataBit(Address.can381,1,4)?"1":"0"));
        sb.append("\r\n安全接近:"+(Address.getInstance().getDataBit(Address.can381,1,5)?"1":"0"));
        sb.append("\r\n安全向前:"+(Address.getInstance().getDataBit(Address.can381,1,6)?"1":"0"));
        sb.append("\r\n安全向后:"+(Address.getInstance().getDataBit(Address.can381,1,7)?"1":"0"));
        sb.append("\r\n安全带:"+(Address.getInstance().getDataBit(Address.can381,2,2)?"系上":"未系"));
        sb.append("\r\n车门关上:"+(Address.getInstance().getDataBit(Address.can381,2,2)?"关":"开"));

       return sb.toString();
    }

    private String getData1()
    {

        /*

        Bit0 = 座位开关                   Bit1 = 脚刹
Bit2 = 前进挡位                Bit3 = 后退挡位                Bit4 = 手刹                    Bit5 = 龟速                         Bit6 = 右转向灯                          Bit7 = 左转向灯                       Bit8 = 双闪灯                        Bit9 = 示廓灯                    Bit10=  近光灯                           Bit11 = 远光灯                Bit12 = 后雾灯                          Bit13 = 安全接近                         Bit14 = 安全接近向前              Bit15 = 安全接近向后
bit16 = 真空泵报警（显示屏）
bit17 = 刹车油液位低（显示屏）

         */

        StringBuilder sb = new StringBuilder();

        sb.append("\r\n真空泵报警:"+(Address.getInstance().getDataBit(Address.can381,2,0)?"1":"0"));
        sb.append("\r\n刹车油液位低:"+(Address.getInstance().getDataBit(Address.can381,2,1)?"1":"0"));

        int can381_6 = Address.getInstance().getData(Address.can381,6,1,"无符号");
        String can381_6String = "N";
        if(can381_6 == 1)
        {
            can381_6String = "D";
        }
        else if(can381_6 == 2)
        {
            can381_6String = "R";
        }
        sb.append("\r\n档位:"+ can381_6String );
        sb.append("\r\n软件版本："+Address.getInstance().getData(Address.can381,7,1,"无符号"));
        sb.append("\r\n液压油压力："+ (new Float(Address.getInstance().getData(Address.can481,0,2,"无符号")) * 0.01f)+"MPa");
        sb.append("\r\n驱动器状态:"+(Address.getInstance().getDataBit(Address.can581,0,0) ? "驱动器准备好":"驱动器未准备好"));
        sb.append("\r\n驱动器使能状态反馈:"+(Address.getInstance().getDataBit(Address.can581,0,1) ? "1":"0"));
        sb.append("\r\n油压故障:"+(Address.getInstance().getDataBit(Address.can581,1,0)?"1":"0"));
        sb.append("\r\n电机驱动器CAN通信超时:"+(Address.getInstance().getDataBit(Address.can581,1,1)?"1":"0"));
        sb.append("\r\n油门开度："+Address.getInstance().getData(Address.can581,2,1,"无符号")+"%");
        sb.append("\r\n主状态机状态："+Address.getInstance().getData(Address.can581,3,1,"无符号"));
        sb.append("\r\n主状态机历史状态："+Address.getInstance().getData(Address.can581,4,1,"无符号"));
        sb.append("\r\n电池仓温度："+ (new Float(Address.getInstance().getData(Address.can481,2,2,"无符号")) * 0.01f)+"°C");


        return sb.toString();
    }



}